const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const createError = require('http-errors');
require('dotenv').config();
const bcrypt = require('bcryptjs');
import type {Ipayload} from '../../utils/jwt';
import jwt from '../../utils/jwt';

class AuthService {
  static async register(data: Ipayload) {
    data.password = bcrypt.hashSync(data.password, 8);
    let user = await prisma.user.create({
      data
    })
    delete user.password;
    user.accessToken = await jwt.signAccessToken(user);
    return user;
  }
  static async login(data: Ipayload) {
    const { email, password } = data;
    const user = await prisma.user.findUnique({
      where: {
        email
      }
    });
    if (!user) {
      console.log('createError==', createError);
      throw createError.NotFound('User not registered')
    }
    const checkPassword = bcrypt.compareSync(password, user.password)
    if (!checkPassword) throw createError.Unauthorized('Email address or password not valid');
    delete user.password
    const accessToken = await jwt.signAccessToken(user)
    return { ...user, accessToken }
  }
  static async all(): Promise<Ipayload> {
    return await prisma.user.findMany();
  }
}

export default AuthService;
